from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.models.class_student import ClassStudent as ClassStudentModel, ClassStudentInDB
from app.schemas.class_student import ClassStudent as ClassStudentSchema, ClassStudentCreate, ClassStudentUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from datetime import datetime

router: APIRouter = APIRouter(prefix="/class-students", tags=["class_students"])

@router.post("/create", response_model=APIResponse[ClassStudentSchema])
def create_class_student(class_student: ClassStudentCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating class student with class_id: {class_student.class_id}, student_id: {class_student.student_id}")
    
    # 检查班级学生关联是否已存在
    db_class_student = db.query(ClassStudentModel).filter(
        ClassStudentModel.class_id == class_student.class_id,
        ClassStudentModel.student_id == class_student.student_id
    ).first()
    if db_class_student:
        logger.warning(f"Class student already registered with class_id: {class_student.class_id}, student_id: {class_student.student_id}")
        return error_response(message="Class student already registered", code=400)
    
    # 创建新班级学生关联
    db_class_student = ClassStudentModel(
        class_id=class_student.class_id,
        student_id=class_student.student_id,
        join_date=class_student.join_date,
        leave_date=class_student.leave_date,
        status=class_student.status,
        create_time=datetime.utcnow(),
        update_time=datetime.utcnow()
    )
    
    db.add(db_class_student)
    db.commit()
    db.refresh(db_class_student)
    
    # 转换为Pydantic模型
    class_student_response = ClassStudentInDB.model_validate(db_class_student)
    
    logger.info(f"Class student created successfully with ID: {db_class_student.id}")
    return success_response(data=class_student_response, message="Class student created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[ClassStudentSchema]])
def read_class_students(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching class students with skip: {skip}, limit: {limit}")
    
    class_students = db.query(ClassStudentModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    class_students_response = [ClassStudentInDB.model_validate(class_student) for class_student in class_students]
    total = db.query(ClassStudentModel).count()
    
    logger.info(f"Found {len(class_students)} class students")
    return paginated_response(
        items=class_students_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{class_student_id}", response_model=APIResponse[ClassStudentSchema])
def read_class_student(class_student_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching class student with ID: {class_student_id}")
    
    db_class_student = db.query(ClassStudentModel).filter(ClassStudentModel.id == class_student_id).first()
    if db_class_student is None:
        logger.warning(f"Class student not found with ID: {class_student_id}")
        return error_response(message="Class student not found", code=404)
    
    # 转换为Pydantic模型
    class_student_response = ClassStudentInDB.model_validate(db_class_student)
    
    logger.info(f"Class student found with ID: {class_student_id}")
    return success_response(data=class_student_response)

@router.put("/{class_student_id}", response_model=APIResponse[ClassStudentSchema])
def update_class_student(class_student_id: int, class_student: ClassStudentUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating class student with ID: {class_student_id}")
    
    db_class_student = db.query(ClassStudentModel).filter(ClassStudentModel.id == class_student_id).first()
    if db_class_student is None:
        logger.warning(f"Class student not found with ID: {class_student_id}")
        return error_response(message="Class student not found", code=404)
    
    # 更新班级学生关联信息
    update_data = class_student.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_class_student, key, value)
    
    db_class_student.update_time = datetime.utcnow()
    db.commit()
    db.refresh(db_class_student)
    
    # 转换为Pydantic模型
    class_student_response = ClassStudentInDB.model_validate(db_class_student)
    
    logger.info(f"Class student updated successfully with ID: {class_student_id}")
    return success_response(data=class_student_response, message="Class student updated successfully")

@router.delete("/{class_student_id}", response_model=APIResponse[None])
def delete_class_student(class_student_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting class student with ID: {class_student_id}")
    
    db_class_student = db.query(ClassStudentModel).filter(ClassStudentModel.id == class_student_id).first()
    if db_class_student is None:
        logger.warning(f"Class student not found with ID: {class_student_id}")
        return error_response(message="Class student not found", code=404)
    
    db.delete(db_class_student)
    db.commit()
    
    logger.info(f"Class student deleted successfully with ID: {class_student_id}")
    return success_response(message="Class student deleted successfully")
